package com.furschina.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.DatabaseRetrievalMethod;
import org.hibernate.search.query.ObjectLookupMethod;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import cn.wooshai.core.dao.hibernate.GenericHibernateDao;

import com.furschina.model.Article;
import com.furschina.model.User;
import com.furschina.vo.ArticlePage;

@Repository
public class ArticleDao extends GenericHibernateDao<Article> {
	public List<Article> getArticleListByCreator(User creator) {
		String sql = "from Article as a where a.creator = ? ";
		return this.findAll(sql, true, creator);
	}

	public List<Article> getArticleListByPublished(boolean isPublished) {
		String sql = "from Article as a where a.published = ?";
		return this.findAll(sql, true, isPublished);
	}

	public List<Article> search(final ArticlePage pm) {
		return this.getHibernateTemplate().executeWithNativeSession(
				new HibernateCallback<List<Article>>() {

					@Override
					@SuppressWarnings("unchecked")
					public List<Article> doInHibernate(Session session)
							throws HibernateException, SQLException {
						FullTextSession fsession = Search
								.getFullTextSession(session);
						FullTextQuery query = fsession
								.createFullTextQuery(
										fsession.getSearchFactory()
												.buildQueryBuilder()
												.forEntity(persistentClass)
												.get().keyword()
												.onFields("title", "content")
												.matching(pm.getQ())
												.createQuery(), persistentClass)
								.initializeObjectsWith(
										ObjectLookupMethod.SECOND_LEVEL_CACHE,
										DatabaseRetrievalMethod.FIND_BY_ID)
								.setMaxResults(pm.getMaxRecord())
								.setFirstResult(pm.getFirstRecord())
								.setResultTransformer(
										Transformers
												.aliasToBean(persistentClass));
						pm.setTotalRecords(query.getResultSize());
						return query.list();
					}
				});
	}

}